package com.medium.house.biz;

import com.medium.house.entity.HouseInfo;
import com.medium.house.entity.HousePicture;
import com.medium.house.entity.HousePointRef;
import com.medium.house.enums.HouseTypeEnum;
import com.medium.house.request.HouseSellPointRequestDto;
import com.medium.house.response.HousePicsDto;
import com.medium.house.response.HouseIndexDto;
import com.medium.house.response.HouseInfoDto;
import com.medium.house.service.HouseBannerService;
import com.medium.house.service.HouseInfoService;
import com.medium.house.service.HousePictureService;
import com.medium.house.service.HousePointRefService;
import com.medium.house.utils.FileUtil;
import com.medium.house.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @Author : wang.yu
 * @Description :
 * @Date: Created in 2018/2/16 0016  20:12
 * @Modified By
 */

@Component
@Slf4j
public class HouseInfoBiz {
    @Autowired
    private HouseInfoService houseInfoService;
    @Autowired
    private HousePictureService housePictureService;
    @Autowired
    private HousePointRefService housePointRefService;
    @Autowired
    private HouseBannerService bouseBannerService;

    /**
     * 暂时先这样放着，等全部可配置后，此路径配置到文件中
     */
    @Value("${image.qiniu.default.img}")
    private String default_img;

    /**
     * 暂时先这样放着，等全部可配置后，此路径配置到文件中
     */
    @Value("${image.qiniu.url}")
    private String img_url;
    @Value("${image.qiniu.accessKey}")
    private String accessKey;
    @Value("${image.qiniu.secretKey}")
    private String secretKey;
    @Value("${image.qiniu.bucket}")
    private String bucket;

    @Transactional(propagation = Propagation.REQUIRED)
    public int release(HouseInfo houseInfo){
        log.info("HouseInfoBiz release({})",houseInfo);
        if (houseInfoService.add(houseInfo) == 0 ){
            log.error("HouseInfoBiz release houseInfoService.add(houseInfo) Exception");
            throw new RuntimeException("HouseInfoBiz release houseInfoService.add(houseInfo) Exception");
        }
        //保存卖点关联表
        List<Map<String,Object>>  houseSellPointList = JacksonUtils.extractList(houseInfo.getSellPoint(),new ArrayList<Map<String,Object>>());
        for (Map<String,Object> map : houseSellPointList){
            if (null != map.get("code")){
                HousePointRef sellPointRef = new HousePointRef();
                sellPointRef.setHouseInfoId(houseInfo.getId());
                sellPointRef.setHousePoint(Long.valueOf(map.get("code").toString()));
                if (housePointRefService.add(sellPointRef) == 0 ){
                    log.error("HouseInfoBiz release housePointRefService.add(sellPointRef) Exception");
                    throw new RuntimeException("HHouseInfoBiz release housePointRefService.add(sellPointRef) Exception");
                }
            }
        }
        return 1;
    }


    /**
     * 上传照片
     * @param houseInfo
     * @param picture
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public int upLoadHousePicture(HouseInfo houseInfo, MultipartFile picture) throws Exception{
        log.info("HouseInfoBiz upLoadHousePicture({})",houseInfo);
        if (null == houseInfo ){
            log.info("HouseInfoBiz upLoadHousePicture ==> ({})","房屋信息不存在");
            return 0;
        }
        //上传图片完成后，记录上传图片数据.
        String defaultUrl = img_url + picFile(picture);
        HousePicture housePicture = new HousePicture().initialize();
        housePicture.setUrl(defaultUrl);
        housePicture.setOpenid(houseInfo.getOpenid());
        housePicture.setHouseId(houseInfo.getId());
        housePicture.setType(houseInfo.getType());
        housePicture.setRemark("图片数据");
        housePicture.setCreatedAt(new Date());
        housePicture.setUpdatedAt(new Date());
        if (housePictureService.add(housePicture) == 0){
            log.error("HouseInfoBiz upLoadHousePicture housePictureService.add(housePicture) Exception");
            throw new RuntimeException("HouseInfoBiz upLoadHousePicture housePictureService.add(housePicture) Exception");
        }
        //更新默认图片
        if (StringUtils.isEmpty(houseInfo.getHousePicture()) || houseInfo.getHousePicture().equals(default_img)){
            houseInfo.setHousePicture(defaultUrl);
            if (houseInfoService.update(houseInfo) == 0 ){
                log.error("HouseInfoBiz upLoadHousePicture houseInfoService.update(houseInfo) Exception");
                throw new RuntimeException("HouseInfoBiz upLoadHousePicture houseInfoService.update(houseInfo) Exception");
            }
        }
        return 1;
    }

    /**
     * 七牛云上传照片
     * @param file
     * @return
     * @throws RuntimeException
     */
    private String picFile(MultipartFile file) throws RuntimeException {
        try {
            String qnyFileName = FileUtil.qnyFileUpInputStream(file.getInputStream(), accessKey, secretKey, bucket);
            return qnyFileName;
        } catch (Exception e) {
            log.error("HouseInfoBiz upFile IOException，e:{}",e);
            throw new RuntimeException("HouseInfoBiz upFile IOException");
        }
    }

    /**
     * 详情
     * @param houseID
     * @return
     */
    public HouseInfoDto getHouserInfo(Long houseID,int status){
        HouseInfoDto dto = new HouseInfoDto();
        //获取房屋信息
        Map houseInfo = houseInfoService.get(houseID,status);
        if (houseInfo.get("sellPoint") instanceof String){
            houseInfo.put("sellPoint",JacksonUtils.extractList(houseInfo.get("sellPoint").toString(),new ArrayList<HouseSellPointRequestDto>()));
        }
        dto.setHouseInfo(houseInfo);
        //获取房屋对应图片信息
        List<HousePicsDto> housePictureList = housePictureService.getHousePictureByHouserID(houseID);
        if (null == housePictureList || housePictureList.size() ==0){
            HousePicsDto housePicsDto = new HousePicsDto();
            housePicsDto.setPic(default_img);
            housePictureList.add(housePicsDto);
        }
        dto.setHousePics(housePictureList);
        return dto;
    }

    /**
     * 首页
     * @return
     */
    public HouseIndexDto index(){
        List<HousePicsDto> houseBannerDto = bouseBannerService.getAllBanner(1);
        int offset = 0;
        int limit = 5;
        int sort = 2;
        int order = 0;
        List<Map<String,Object>> houseInfoList = houseInfoService.getByPageToOverViewForJoin(offset,limit,sort,order,
                0,1,"","","","","","");
        for (Map<String,Object> map: houseInfoList) {
            if (map.get("sellPoint") instanceof String){
                map.put("sellPoint",JacksonUtils.extractList(map.get("sellPoint").toString(),new ArrayList<HouseSellPointRequestDto>()));
            }
        }
        HouseIndexDto houseIndexDto = new HouseIndexDto();
        houseIndexDto.setBanner(houseBannerDto);
        houseIndexDto.setHouseList(houseInfoList);
        return houseIndexDto;
    }
}
